package com.intramirror.product.service.impl;

import com.aliyun.oss.OSSClient;
import com.intramirror.product.config.OSSConfig;
import com.intramirror.product.service.IOssManagementService;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * Created on 2018/7/6.
 * @author 123
 */
@Service
public class OssManagementServiceImpl implements IOssManagementService {

    @Autowired
    OSSConfig ossConfig;

    private static OSSClient ossClient = null;

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        synchronized (this) {
            if (ossClient == null) {
                initOssClient();
            }
        }

        String fileName = UUID.randomUUID().toString();
        ossClient.putObject(ossConfig.getBucketName(), fileName, new ByteArrayInputStream(file.getBytes()));
        return ossConfig.getImgUrl() + fileName;
    }

    private void initOssClient() {
        ossClient = new OSSClient(ossConfig.getEndPoint(), ossConfig.getAccessId(), ossConfig.getAccessKey());
    }
}
